<template>
	<view>
		<!-- 聊天列表 -->
		<scroll-view scroll-y="true" style="position: absolute;top: 0;left: 0;right: 0;bottom: 100rpx;"
			:scroll-into-view="scrollInto" scroll-with-animation>
			<block v-for="(item,index) in list">
				<view :id="'chart' + index">
					<userChartList :item="item" :index="index" :pretime="index > 0 ? list[index - 1].create_time : 0">
					</userChartList>
				</view>
			</block>
		</scroll-view>

		<!-- 底部输入框 -->
		<bottomBtn @submit="submit"></bottomBtn>
	</view>
</template>

<script>
	import userChartList from '@/components/user-chart/user-chart-list.vue'
	import bottomBtn from '@/components/common/bottom-btn.vue'
	export default {
		components: {
			userChartList,
			bottomBtn
		},
		data() {
			return {
				content: '',
				scrollInto: '',
				list: []
			}
		},
		onLoad(e) {
			console.log(e)
			if(!e.user){
				uni.navigateBack({
					delta: 1
				});
				return uni.showToast({
					title: '聊天对象不存在',
					icon:'none'
				});
			}
			let ToUser = JSON.parse(e.user)
			//创建聊天
			this.$store.commit('createToUser',ToUser)
			//获取当前聊天记录
			this.$store.dispatch('getChatDetailToUser',).then(list => {
				console.log('[user-chat]获取当前聊天对象的聊天记录',list);
				this.list = list
			})
			//开启监听接收消息
			uni.$on('UserChat',(res) => {
				console.log('[user-chat]接收消息',res)
				if(res.from_id === ToUser.user_id){
					this.renderPage({
						data:res,
						send:false
					})
				}
			})
		},
		onReady() {
			this.pageToBottom()
		},
		beforeDestroy() {
			this.$store.commit('closeToUser')
		},
		
		methods: {
			// 渲染到页面
			renderPage(e){
				this.$store.dispatch('formatChatDetailObject',e).then(msg=>{
					this.list.push(msg)
					// 滚动到底部
					this.pageToBottom()
				})
			},
			//发送消息
			async submit(data) {
				//组织发送格式
				let result = await this.$store.dispatch('sendChatMessage',{
					data,
					type:'text'
				})
				//请求发送接口
				this.$H.post('/chat/send',result,{
					token:true
				}).then( res => {
					this.renderPage({
						data:result,
						send:true
					})
				})
			},
			//进入页面定位到最后一条消息
			pageToBottom() {
				setTimeout(() => {
					let lastIndex = this.list.length - 1
					if (lastIndex < 0) return;
					this.scrollInto = 'chart' + lastIndex
				}, 300)
			}
		}
	}
</script>

<style>

</style>
